package com.paddyi.jwt;//package com.springcloud.jwt;

import com.paddyi.commons.http.AuthHeader;
import com.paddyi.commons.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.auth.login.AccountExpiredException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT验证过滤器，放在用户密码过滤器之前 解析token中用户信息，并赋予上下文
 * 也就是说,所有的认证逻辑可以放在这里
 * @author paddy
 *
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtConfigProperty jwtConfig;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String authHeader = AuthHeader.getAuthHeader(request,jwtConfig.getHeader());
        String tokenHead = jwtConfig.getTokenHead(); //获取配置文件的token开头
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith(tokenHead)) { //验证token是否为空,验证是否为配置文件的开头
            String authToken = authHeader.substring(tokenHead.length());//去掉开头
            try {
                if (jwtUtil.validateToken(authToken)) { //验证token是否合法
                    String userIdAndRoles = jwtUtil.getSubjectFromToken(authToken); // 获取userid和roles

                    String redisRe = stringRedisTemplate.opsForValue().get(userIdAndRoles);
                    if(StringUtils.isNotBlank(redisRe)){
                        //如果有认证逻辑,或者是延长token时间可以写到这里
                        //这里的信息其实是可以随便填写的,因为要创建下面的SecurityContextHolder,
                        //这个本来是存session信息的，我们用jwt实现就无所谓了
                        // 由于这个SecurityContextHolder每次连接后都会清除掉,所以也不占什么资源
                        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                        authorities.add(new SimpleGrantedAuthority(userIdAndRoles));
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userIdAndRoles, null, authorities);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }else{
                        throw new AccountExpiredException();
                    }
                }
            }catch (Exception e) {
                logger.info("登录异常");
            }
        }
        filterChain.doFilter(request, response);

    }

}
